import request from '@/utils/request';
import store from '@/store'
export function randomString(length = 32) {
	var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var result = '';
	for (var i = length; i > 0; --i)
		result += str[Math.floor(Math.random() * str.length)];
	return result;
}
//获取oss配置
export function getOss() {
	return request({
		url: '/third/oss/policy',
		method: 'get',
		params: {
			bucket: 'larp-gbo'
		}
	})
}
export async function getOssUrl(path) {
	await store.dispatch('getOss')
	return new Promise((resolve, reject) => {
		const signatureObj = store.getters.oss;
		const fix = path.substr(path.lastIndexOf('.'));
		const name = randomString() + fix; //随机文件名称
		const key = signatureObj.dir + name;
		const formData = {
			name: name,
			key,
			policy: signatureObj.policy,
			OSSAccessKeyId: signatureObj.accessKeyId,
			success_action_status: "200",
			signature: signatureObj.signature,
		}
		uni.uploadFile({
			url: signatureObj.host,
			filePath: path,
			formData,
			name: 'file',
			success: () => {
				const value = signatureObj.host + '/' + key
				resolve({
					url: value,
					name
				})
			},
			fail: (e) => {
				console.log(e)
				reject()
			}
		})
	})
}

//获取oss配置
export function getAppParam() {
	return request({
		url: '/third/oss/getAppParam'
	})
}
